package com.wuliang.generate.common.core.adapter.jpa.impl;


import com.wuliang.generate.common.core.adapter.jpa.EntityFieldTypeAdapter;
import com.wuliang.generate.common.core.basic.BasicEntity;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Predicate;

/**
 * 实体类数字字段适配器
 *
 * @author 邬魉
 */
public class NumberFieldTypeAdapter implements EntityFieldTypeAdapter<Number> {

    @Override
    public Predicate toPredicate(Class<? extends BasicEntity> entity, CriteriaBuilder criteriaBuilder,
                                 String fieldName, Number fieldValue, From<Object, Number> from) {
        if (entity.isAssignableFrom(from.get(fieldName).getJavaType())) {
            // 如果查询的是主键则为 ID=${[value]}
            return criteriaBuilder.equal(from.get(fieldName).get("ID"), fieldValue.intValue());
        } else {
            // 否则直接赋值为 [column_name]=${column_name}
            return criteriaBuilder.equal(from.get(fieldName), fieldValue.intValue());
        }
    }
}
